package edu.jhu.cs.oose.scheduleit.services.impl;

import java.util.Iterator;
import java.util.List;
import org.springframework.dao.DataIntegrityViolationException;
import edu.jhu.cs.oose.scheduleit.dao.UserDao;
import edu.jhu.cs.oose.scheduleit.services.UserService;
import edu.jhu.cs.oose.scheduleit.util.Attribute;
import edu.jhu.cs.oose.scheduleit.util.JoinStatus;
import edu.jhu.cs.oose.scheduleit.util.UserAttributeKind;
import edu.jhu.cs.oose.scheduleit.vo.Group;
import edu.jhu.cs.oose.scheduleit.vo.User;

/**
 * The implementation class of the UserService interface
 * @author oosegroup2
 *
 */
public class UserServiceImpl implements UserService {

	
	/**
	 * The data access object related to user
	 */
	private UserDao userDao;

	/**
	 * The setter for userDao
	 * @param userDao
	 * @throws DataBaseException
	 */
	public void setUserDao(UserDao userDao) throws DataBaseException {
		this.userDao = userDao;
	}

	@Override
	public User login(String email, String password) throws DataBaseException {
		return this.userDao.get(email, password);
	}

	public User getUser(String email) throws DataBaseException{
		return this.userDao.get(email);
	}
	@Override
	public User register(Attribute attribute) throws DataBaseException {
		try {
			User user = new User();
			user.setEmail((String)attribute.getValue(UserAttributeKind.EMAIL));
			this.setAttribute(user, attribute);
			this.userDao.save(user);
			return user;
		} catch (DataIntegrityViolationException e) {
			return null;
		} catch (Exception e) {
			throw new DataBaseException(e);
		}
	}

	@Override
	public void update(User user, Attribute attribute)
			throws DataBaseException {
		try {
			this.setAttribute(user, attribute);
			this.userDao.save(user);
		}catch (Exception e) {
			throw new DataBaseException(e);
		}
	}

	
	private void setAttribute(User user, Attribute attribute){
		
		Iterator<Enum<?>> attrIterator = attribute.getAttributeKinds().iterator();
		while (attrIterator.hasNext()){
			UserAttributeKind attr = (UserAttributeKind) attrIterator.next();
			switch(attr){
				case PASSWORD:
					user.setPassword((String)attribute.getValue(UserAttributeKind.PASSWORD));
					break;
				case NICK_NAME:
					user.setNickName((String) attribute
							.getValue(UserAttributeKind.NICK_NAME));
					break;
					
			}
		}
		
	}
	
	@Override
	public List<Group> getGroup(User user, JoinStatus status, int offset,
			int limit) throws DataBaseException {
		try {
			return this.userDao.getGroup(user, status, offset, limit);
		} catch (Exception e) {
			throw new DataBaseException(e);
		}
	}

	@Override
	public int getGroupCount(User user, JoinStatus status)
			throws DataBaseException {
		try {
			return this.userDao.countGroup(user, status);
		} catch (Exception e) {
			throw new DataBaseException(e);
		}
	}

}
